package com.cheer.ba.choosepic.ui;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.cheer.ba.R;
import com.cheer.ba.choosepic.util.Bimp;
import com.cheer.ba.choosepic.util.ImageItem;
import com.cheer.ba.choosepic.util.PublicWay;
import com.cheer.ba.choosepic.zoom.PhotoView;
import com.cheer.ba.choosepic.zoom.ViewPagerFixed;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * GalleryAty
 * Author: hq
 * Email: 834138841@qq.com
 * Comment: 用于进行图片浏览时的界面
 * Date: 2017/7/27  15:00
 */
public class GalleryChooseAty extends BaseCommAty {

    //删除按钮
    @BindView(R.id.id_pic_del_btn)
    Button mBtnDel;
    //下载按钮
    @BindView(R.id.id_pic_down_txt)
    ImageView mImgDown;
    //选择照片
    @BindView(R.id.id_choose_pic_check)
    CheckBox mCheckBox;
    //图片数量
    @BindView(R.id.id_pic_num_txt)
    TextView mTxtPicNun;
    //图片中部展示
    @BindView(R.id.id_pic_look_viewpager)
    ViewPagerFixed mViewPager;
    private MyPageAdapter adapter;
    //用于存储查看图片的数据
    private ArrayList<View> listViews = null;

    //记录是否显示删除
    private boolean isDel;
    //记录图片浏览的当前位置
    private int position;

    @Override
    protected boolean isTitleBarShow() {
        return false;
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.plugin_camera_gallery, null, false));
    }

    @Override
    public void initView() {
        position = getIntent().getIntExtra(IntentKey.General.KEY_POS, Constants.DEFAULTVALUE);
        mBtnDel.setVisibility(View.GONE);
        mImgDown.setVisibility(View.GONE);
        mCheckBox.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        for (int i = 0; i < Bimp.allPics.size(); i++) {
            //相册中浏览
            initListViews(Bimp.allPics.get(i).getBitmap());
        }
        adapter = new MyPageAdapter(listViews);
        mViewPager.setAdapter(adapter);
        mViewPager.setPageMargin((int) getResources().getDimensionPixelOffset(R.dimen.ui_10_dip));
        mViewPager.setOnPageChangeListener(pageChangeListener);
        mViewPager.setCurrentItem(position);
        handPicCheck(position);
    }

    private void initListViews(Bitmap bm) {
        if (listViews == null)
            listViews = new ArrayList<View>();
        PhotoView img = new PhotoView(this);
        img.setBackgroundColor(0xff000000);
        img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        img.setImageBitmap(bm);
        listViews.add(img);
    }

    public void handPicCheck(int postion) {
        //判断照片是否选中
        handPicNum();
        ImageItem item = Bimp.allPics.get(postion);
        if (Bimp.tempSelectBitmap.contains(item)) {
            mCheckBox.setChecked(true);
            mCheckBox.setBackgroundResource(R.drawable.ic_agree_oil_ask);
        } else {
            mCheckBox.setChecked(false);
            mCheckBox.setBackgroundResource(R.drawable.ic_agree_oil_ask_off);
        }
    }

    private boolean removeOneData(ImageItem imageItem) {
        if (Bimp.tempSelectBitmap.contains(imageItem)) {
            return true;
        }
        return false;
    }

    /**
     * 处理下方图片定位
     */
    public void handPicNum() {
        mTxtPicNun.setText(Bimp.tempSelectBitmap.size() + "/" + PublicWay.total_num);
    }

    private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
        public void onPageSelected(int arg0) {
            position = arg0;
            handPicCheck(position);
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageScrollStateChanged(int arg0) {
        }
    };

    @OnClick({R.id.id_pic_back_txt, R.id.id_choose_pic_check})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_pic_back_txt:
                //返回按钮
                finish();
                break;
            case R.id.id_choose_pic_check:
                //点击选择照片
                LogUtils.LogD("gallery", mCheckBox.isChecked() + "-------");
                if (mCheckBox.isChecked()) {
                    if (Bimp.tempSelectBitmap.size() >= PublicWay.total_num) {
                        mCheckBox.setChecked(false);
                        mCheckBox.setBackgroundResource(R.drawable.ic_agree_oil_ask_off);
                        ToastUtil.showToast("最多只能选择9张照片");
                        return;
                    }
                    mCheckBox.setBackgroundResource(R.drawable.ic_agree_oil_ask);
                    Bimp.tempSelectBitmap.add(Bimp.allPics.get(position));
                } else {
                    mCheckBox.setBackgroundResource(R.drawable.ic_agree_oil_ask_off);
                    Bimp.tempSelectBitmap.remove(Bimp.allPics.get(position));
                }

                handPicNum();

                BaseEvent event = new BaseEvent();
                event.type = IntentKey.General.KEY_FINISH;
                EventBus.getDefault().post(event);
                break;
        }
    }

    /**
     * 图片浏览的适配器
     */
    class MyPageAdapter extends PagerAdapter {
        private ArrayList<View> listViews;
        private int size;

        public MyPageAdapter(ArrayList<View> listViews) {
            this.listViews = listViews;
            size = listViews == null ? 0 : listViews.size();
        }

        public void setListViews(ArrayList<View> listViews) {
            this.listViews = listViews;
            size = listViews == null ? 0 : listViews.size();
        }

        public int getCount() {
            return size;
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPagerFixed) arg0).removeView(listViews.get(arg1 % size));
        }

        public void finishUpdate(View arg0) {
        }

        public Object instantiateItem(View arg0, int arg1) {
            try {
                ((ViewPagerFixed) arg0).addView(listViews.get(arg1 % size), 0);
            } catch (Exception e) {
            }
            return listViews.get(arg1 % size);
        }

        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    }

}
